require 'json'
require "tweetGrammar"

class TweeController < ApplicationController
  before_filter :authenticate_user!
  
  # GET /operations/index
  # GET /operations/index.xml
  def index
    @operations = current_user.operations.all.map { |o| o.external_format }

    respond_to do |format|
      format.html { render :index }
      format.json { render :json  => @operations }
    end
  end

  def tweet_operation
    operations = TweeHelper::process_tweets(current_user, params[:tweet])
    operations.each {|o| o.record_date = params[:date]} if params[:date]

    respond_to do |format|
      if operations.all? {|o| o.save!}
        params["op"] = operations[0].external_format

        format.html { render :partial => 'index_operation_fields', :locals => {:operation => params["op"]} }
        if (operations.size == 1)
          format.json { render :json  => params["op"] }
        else
          format.json { render :json  => operations.map { |o| o.external_format } }
        end
      else
        format.html { redirect_to :action => "index" }
      end
    end
  end

  def add_operation(operation_params)
    operationRespond(Operation.from_options(current_user, operation_params))
  end

  def del_operation
    respond_to do |format|
      if Operation.delete(params[:id])
        format.json { render :json => {:id => params[:id]}.as_json }
      else
        render_error(format)
      end
    end
  end

  def update_operation_ (id, options)
    Operation.transaction do
      if Operation.delete(id)
        add_operation(options)
      else
        respond_to { |format| render_error(format) }
      end
    end
  end

  def update_operation
    if params[:record] && (record = JSON.parse(params[:record]))
      if record[:value].kind_of? String
        record[:value] = TweetGrammar.parse_money(record[:value])
      end

      update_operation_(record["id"], record)
    else
      update_operation_(params[:id], params["op"])
    end
  end

  private
    def render_message(format, message)
      format.html { render :text => message }
      format.json { render :text => message }
    end

    def render_ok(format)
      render_message(format, "Ok")
    end

    def render_error(format)
      render_message(format, "Error")
    end

    def operationRespond(operation)
      respond_to do |format|
        if operation.save
          format.html { render :partial => 'index_operation_fields', :locals => {:operation =>  operation.external_format} }
          format.json { render :json => operation.external_format }
        else
          format.html { render :text => operation.errors }
          format.json { render :json => operation.errors.as_json }
        end
      end
    end
  
end


